package com.zz.util;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class EditPdfUtil {

    @Value("${mergePdfFolder}")
    private String outputFolder;

    public void MergePdf(List<File> files, String mergePath) throws IOException {
        PDFMergerUtility mergePdf = new PDFMergerUtility();

        for (File f : files) {
            if (f.exists() && f.isFile()) {
                mergePdf.addSource(f);
            }
        }

        mergePdf.setDestinationFileName(mergePath);
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    }

//  public static void main(String[] args) throws Exception {
//    PDFMergerUtility mergePdf = new PDFMergerUtility();
////    要合成的pdf所在的文件夾
//    String folder = "PDF";
//
//     System.out.println(folder);
//     String destinationFileName = "合成.pdf";
//
//     String[] filesInFolder = getFiles(folder);
//     for (int i = 0; i < filesInFolder.length; i++)
//       mergePdf.addSource(folder + File.separator + filesInFolder[i]);
//     mergePdf.setDestinationFileName(destinationFileName);
//     mergePdf.mergeDocuments();
//     System.out.print("合并完成");
//   }

    public int DelPdf(String oldpdfpath, String newpdfpath, int fromp, int endp) {
        File oldfile = new File(oldpdfpath);
        PDDocument document = new PDDocument();
        try {
            document = PDDocument.load(oldfile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int noOfPages = document.getNumberOfPages();
        System.out.println("这个文件共有"+noOfPages+"页");
        if (fromp <= 0 || endp <= 0 || fromp > endp || fromp > noOfPages || endp > noOfPages) {
            System.out.println("页数范围有错误");

            return -1;

        } else {
            int j=endp-fromp+1;

            for (int i = 1; i <= j; i++) {
                document.removePage(fromp - 1);
            }
        }
//        if(flag == 0)
//            document.removePage(0);
//        else if(flag == 1) {
//            document.removePage(noOfPages-1);
//        } else {
//            document.removePage(flag-1);
//        }
        try {
            document.save(newpdfpath);
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("删页完毕");
        return 1;
    }

}
